package com.example.demo.service;

import com.example.demo.bean.CmsArticle;
import com.example.demo.bean.CmsComment;

import com.example.demo.mapper.CmsArticleMapper;
import com.example.demo.mapper.CmsCommentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class CmsCommentService {
    @Autowired
    CmsCommentMapper commentMapper;
    @Autowired
    CmsArticleMapper articleMapper;

    public boolean saveOrUpdate(String id, String content, String artId, String memberName) {
        CmsComment c = new CmsComment();
        if (artId != null) {
            if (articleMapper.selectByPrimaryKey(artId) == null) {
                return false;
            }
        }
        if (id != null && !"".equals(id)) {
            c = commentMapper.selectByPrimaryKey(id);
            if (c == null) {
                return false;
            }
            c.setContent(content);
            c.setArtId(artId);
            c.setMemberName(memberName);
            c.setCommentDate(new Date());
            c.setStatus("待审核");
            commentMapper.updateByPrimaryKey(c);
            return true;
        } else {
            c.setId(UUID.randomUUID().toString());
            c.setContent(content);
            c.setArtId(artId);
            c.setMemberName(memberName);
            c.setCommentDate(new Date());
            c.setStatus("待审核");
            commentMapper.insert(c);
            return true;
        }
    }

    public int delete(String id) {
        int i = commentMapper.deleteByPrimaryKey(id);
        return i;

    }

    public List<CmsComment> all() {
        return commentMapper.selectAll();
    }

    public String deleteByIds(String[] ids) {
        ArrayList<String> suc = new ArrayList<String>();
        ArrayList<String> noExist = new ArrayList<String>();
        if (ids != null && ids.length > 0) {
            for (String id : ids) {
                int i = delete(id);
                if (i == 0) {
                    noExist.add(id);
                }
                if (i == 1) {
                    suc.add(id);
                }
            }
            String str = "success:";
            if (suc.size() > 0) {
                str += "成功删除了" + suc + "!";
            }
            if (noExist.size() > 0) {
                str += "评论" + noExist + "不存在";
            }
            return str;
        } else {
            return "请输入要删除的评论编号";
        }
    }
    public boolean updateState(String comId,String state) {
        int i = commentMapper.updateStateById(comId, state);
        if (i == 0) {
            return false;
        } else {
            return true;
        }
    }
}
